package com.stars.easyms.schedule.handler.mvchandler;

import com.stars.easyms.schedule.bean.DataMsg;
import com.stars.easyms.schedule.bean.DbScheduleUserInfo;
import com.stars.easyms.schedule.enums.LoginStatus;
import com.stars.easyms.schedule.service.DistributedScheduleService;
import com.stars.easyms.schedule.util.HashUtil;
import com.stars.easyms.schedule.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 页面跳转处理类
 *
 * @author guoguifang
 */
public class DbSchedulePermissionMvcHandler extends BaseDbScheduleMvcHandler {

    @DbSchedulePost(value = "login")
    public DataMsg login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
            DataMsg dataMsg = DataMsg.getFailDataMsg();
            dataMsg.setMsg("UserName and password cannot be empty!");
            return dataMsg;
        }
        DbScheduleUserInfo dbScheduleUserInfo = new DbScheduleUserInfo();
        dbScheduleUserInfo.setUserName(userName);
        dbScheduleUserInfo.setUserPassword(HashUtil.sha1(password));
        dbScheduleUserInfo = DistributedScheduleService.getInstance().getDbScheduleUserInfo(dbScheduleUserInfo);
        if (dbScheduleUserInfo == null) {
            DataMsg dataMsg = DataMsg.getFailDataMsg();
            dataMsg.setMsg("UserName or password is not correct!");
            return dataMsg;
        }
        String loginToken = !isUseSso() && StringUtils.isNotBlank(dbScheduleUserInfo.getLoginToken()) ? dbScheduleUserInfo.getLoginToken() : UUID.randomUUID().toString();
        if (updateLoginTime(userName, loginToken, dbScheduleUserInfo.getVersion()) > 0) {
            DataMsg dataMsg = DataMsg.getSuccessDataMsg();
            dataMsg.setAttribute("userName", userName);
            dataMsg.setAttribute("loginToken", loginToken);
            return dataMsg;
        }
        DataMsg dataMsg = DataMsg.getFailDataMsg();
        dataMsg.setMsg("Logon failed, please try again later!");
        return dataMsg;
    }

    @DbSchedulePost(value = "checkPermission")
    public DataMsg checkPermission(HttpServletRequest request) {
        LoginStatus loginStatus = getLoginStatus(request);
        if (LoginStatus.SUCCESS == loginStatus) {
            return DataMsg.getSuccessDataMsg();
        }
        DataMsg dataMsg = DataMsg.getFailDataMsg();
        dataMsg.setStatus("loginFail");
        dataMsg.setMsgCode(loginStatus.getCode());
        return dataMsg;
    }

    @Override
    public String getPath() {
        return "/schedule/permission";
    }

    @Override
    public LoginStatus checkAndRefreshLoginStatus(HttpServletRequest request) {
        return LoginStatus.SUCCESS;
    }
}
